import { ref } from 'vue';
import { saveExamCopyCountForUserApi, queryExamCopyCountForUserApi, queryExamCutCountForUserApi, saveExamCutCountForUserApi } from '#/api/manage/examination-mgr';
import { getExamInfoForUserApi } from '#/api/manage/examination-mgr';
import type { ExamInfo } from '#/api/manage/type';
import { calculateExamEndTime } from '../calculateExamEndTime';
import dayjs from 'dayjs';

export function useExamInfo(examId: string) {
  const examInfo = ref<ExamInfo>();
  const endTime = ref('');

  const refresh = async () => {
    const t0 = performance.now();
    const res = await getExamInfoForUserApi(examId);
    const t1 = performance.now();
    // 使用 RTT/2 作为近似网络延迟，减少偏差
    const latency = (t1 - t0) / 2;
    const serverNowMs = (res.currentTime ? new Date(res.currentTime).getTime() : Date.now()) + latency;

    examInfo.value = {
      ...res,
      currentTime: dayjs(serverNowMs).format('YYYY-MM-DD HH:mm:ss')
    } as ExamInfo;

    endTime.value = calculateExamEndTime(
      examInfo.value?.beginTime || '',
      examInfo.value?.duration || 0
    );
  };

  // 首次加载
  refresh();

  return { examInfo, endTime, refresh };
}

// 查询用户考试切屏次数
export const useFetchCutCount = (examScoreId: string) => {
  const cutCount = ref(0);
  queryExamCutCountForUserApi(examScoreId).then(count => {
    cutCount.value = count ?? 0;
  });
  return cutCount;
};

export const saveCutCount = (examScoreId: string) => {
  return saveExamCutCountForUserApi(examScoreId)
    .then(res => {
      console.log('保存切屏次数成功', res);
      return res;
    })
};

// 查询用户考试复制次数
export const useFetchCopyCount = (examScoreId: string) => {
  const copyCount = ref(0);
  // 这里假设 questionId 和 type 需要传递，如果没有可用值可传空字符串
  const params = {
    examScoreId
  };
  queryExamCopyCountForUserApi(params).then(count => {
    copyCount.value = count ?? 0;
  });
  return copyCount;
};

// 保存用户考试复制次数
export const saveCopyCount = (examScoreId: string) => {
  return saveExamCopyCountForUserApi(examScoreId)
    .then(res => {
      console.log('保存复制次数成功', res);
      return res;
    })
    .catch(error => {
      console.error('保存复制次数失败', error);
      throw error;
    });
};
